
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：后台管理员                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-01-04 10:01:02                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： ManagerService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using BestTrader.Cms.Core;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.Core.Repository;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.RmmfSoftServices;
using BestTrader.Cms.RmmfSoftServices.Models;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.ViewModels.WebApi;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;

namespace BestTrader.Cms.Services
{
    public class ManagerService : IManagerService
    {
        private readonly IManagerRepository _repository;
        private readonly IManagerTokenRepository _tokenRepository;
        private readonly IManagerDataRepository _dataRepository;
        private readonly IManagerRoleRepository _roleRepository;
        private readonly IManagerLogRepository _managerLogRepository;
        private readonly ISysSafeHostAddressService _safeHostService;
        private readonly IMapper _mapper;
        private readonly RmmfSoftAccountService _rmmfService;
        private readonly ILogger<ManagerService> _logger;
        private readonly IManagerRoleService _managerRoleService;
        private readonly IManagerBankCardService _managerBankCard;
        private readonly IDESEncryptService _desEncryptService;
        private readonly IConfiguration _configuration;


        public ManagerService(IManagerRepository repository
            , IManagerTokenRepository tokenRepository
            , IManagerDataRepository dataRepository
            , IManagerRoleRepository roleRepository
            , IManagerBankCardService managerBankCard
            , IManagerLogRepository managerLogRepository
            , ISysSafeHostAddressService safeHostService
            , IMapper mapper
            , RmmfSoftAccountService rmmfService
            , ILogger<ManagerService> logger
            , IManagerRoleService managerRoleService
            , IDESEncryptService desEncryptService
            , IConfiguration configuration
           )
        {
            _repository = repository;
            _tokenRepository = tokenRepository;
            _dataRepository = dataRepository;
            _roleRepository = roleRepository;
            _managerLogRepository = managerLogRepository;
            _safeHostService = safeHostService;
            _mapper = mapper;
            _rmmfService = rmmfService;
            _logger = logger;
            _managerBankCard = managerBankCard;
            _managerRoleService = managerRoleService;
            _desEncryptService = desEncryptService;
            _configuration = configuration;

        }

        /// <summary>
        /// 根据角色获取所有用户或代理
        /// </summary>
        /// <param name="managerId"></param>
        /// <param name="roleId"></param>
        /// <param name="isAgent">是否只获取代理</param>
        /// <returns></returns>
        public List<ItemsDetailModel> GetSelfAndChildManagerByManagerIdAndRoleId(string managerId, string roleId, bool isAgent)
        {
            var result = new List<ItemsDetailModel>();

            if (roleId.IsNullOrWhiteSpace())
            {
                var _managerId = 0;
                if (int.TryParse(managerId, out _managerId))
                {
                    var _manager = _repository.Get(_managerId);
                    if (_manager != null)
                    {
                        roleId = _manager.RoleId.ToString();
                    }
                }
            }

            if (roleId.IsNullOrWhiteSpace())
                return result;

            //string conditions = "where IsDelete=0 and State = 1 ";//未删除和已审核
            string conditions = "where IsDelete=0 ";//未删除和已审核
            if (isAgent) conditions += " and RoleId in(3,4,5)";
            switch (roleId)
            {
                case "3":
                    managerId = _managerRoleService.CheckIsAdministrator(managerId);

                    // 营业部 显示下面所有用户
                    conditions += $"and (Id={ managerId } or AddManagerId={ managerId } " +
                        $"or AddManagerId in(select Id from Manager where AddManagerId={ managerId } and State=1 and IsDelete=0) " +
                        $"or AddManagerId in(select Id from Manager where AddManagerId in(select Id from Manager where AddManagerId in(select Id from Manager where AddManagerId={ managerId } and State=1 and IsDelete=0) and State=1 and IsDelete=0)))";
                    break;
                case "4":
                    // 高级代理 显示中级代理及下面直客
                    conditions += $"and (Id={ managerId } or AddManagerId={ managerId } " +
                        $"or AddManagerId in(select Id from Manager where AddManagerId={ managerId } and State=1 and IsDelete=0))";
                    break;
                case "5":
                    // 中级代理只显示下面相关的直客
                    conditions += $"and (Id={ managerId } or AddManagerId={ managerId })";
                    break;
                case "6":
                    // 直客没有相关数据显示
                    conditions += $"and Id={ managerId }";
                    break;
                default:
                    // 一二级管理显示所有菜单
                    break;
            }
            var data = _repository.GetList(conditions).OrderBy(o => o.RoleId);

            if (data != null && data.Any())
            {
                result = data.Select(p => new ItemsDetailModel
                {
                    ItemCode = p.Id.ToString(),
                    ItemName = p.UserName,
                    ItemData = p.RealName
                }).ToList();
            }

            return result;
        }

        public BaseResult AddOrModify(ManagerAddOrModifyModel item, string UserId)
        {
            var result = new BaseResult();
            result.Success = false;
            Manager manager;
            var addManagerId = UserId.ToInt32() ?? 0;
            var now = DateTime.Now;
            if (item.Id == 0)
            {
                //TODO ADD
                manager = _mapper.Map<Manager>(item);
                manager.Password = AESEncryptHelper.Encode(CzarCmsKeys.DefaultPassword, CzarCmsKeys.AesEncryptKeys);
                manager.LoginCount = 0;
                manager.AddManagerId = addManagerId;
                manager.IsDelete = false;
                manager.AddTime = now;
                if (_repository.Insert(manager) > 0)
                {
                    result.Success = true;
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                //TODO Modify
                manager = _repository.Get(item.Id);
                if (manager != null)
                {
                    _mapper.Map(item, manager);
                    manager.ModifyManagerId = addManagerId;
                    manager.ModifyTime = now;
                    if (_repository.Update(manager) > 0)
                    {
                        result.Success = true;
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                }
            }
            return result;
        }

        /// <summary>
        /// 添加或者修改个人信息
        /// </summary>
        /// <param name="item"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public BaseResult AddOrModifyUserInfo(ModifyUserInfoIntput item, string UserId)
        {
            var result = new BaseResult();
            result.Success = false;
            Manager manager;
            var addManagerId = UserId.ToInt32() ?? 0;
            var now = DateTime.Now;

            // Modify
            manager = _repository.Get(item.Id);
            //只有审核通过的用户才能修改资料
            if (manager != null && manager.State == 1)
            {
                _mapper.Map(item, manager);
                manager.State = 0;  //用户修改资料后重新审核 2019/02/22 (APP端提出)
                manager.ModifyManagerId = addManagerId;
                manager.ModifyTime = now;
                //
                using (TransactionScope scope = new TransactionScope())
                {
                    var queryResult = _repository.Update(manager);
                    if (queryResult > 0)
                    {
                        ///删除之前存在的认证图片
                        ///
                        _dataRepository.UpdateDeleteByManagerId(manager.Id);
                        if (item.AuditImages.Any())
                        {
                            foreach (var auditImageUrl in item.AuditImages)
                            {
                                _dataRepository.Insert(new ManagerData
                                {
                                    ImageUrl = auditImageUrl,
                                    ManagerId = manager.Id,
                                    AddTime = now
                                });
                            }
                        }
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                        result.Success = true;
                        scope.Complete();
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
            }
            else if (manager.State == 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.InAuditExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.InAuditExceptionMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
            }
            return result;

        }


        public BaseResult ResetPassword(int managerId, String UserId)
        {
            var result = new BaseResult();
            if (managerId > 0)
            {
                var manager = _repository.Get(managerId);
                if (manager != null)
                {
                    manager.Password = AESEncryptHelper.Encode(CzarCmsKeys.DefaultPassword, CzarCmsKeys.AesEncryptKeys);
                    _repository.Update(manager);
                    _logger.LogWarning($"管理员 UserId：{UserId} 重置了用户 Id:{ manager.Id } UserName:{ manager.UserName }的相关密码！");
                    //成功
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    //失败
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                //失败
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }
            return result;
        }

        public BaseResult DeleteIds(int[] Ids)
        {
            var result = new BaseResult();
            if (Ids.Count() == 0)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonModelStateInvalidMsg;
            }
            else
            {
                var count = _repository.DeleteLogical(Ids);
                if (count > 0)
                {
                    //成功
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    //失败
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            return result;
        }
        /// <summary>
        /// 根据角色查询
        /// </summary>
        /// <param name="model"></param>
        /// <param name="UserId"></param>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public TableDataModel LoadData(ManagerRequestModel model, String UserId, String RoleId)
        {
            var viewList = new List<ManagerListModel>();
            var count = 0;
            //if (!UserId.IsNullOrWhiteSpace() && !RoleId.IsNullOrWhiteSpace())
            //{
            string conditions = "where IsDelete=0 ";//未删除的
            string Key = "";

            #region 获取相关用户的处理逻辑
            var _managers = GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId, false);
            if (_managers.Any()) conditions += $"and Id in({ String.Join(',', _managers.Select(p => p.ItemCode)) }) ";
            #endregion

            #region 查询条件

            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and (UserName like @Key or RealName like @Key or Mobile like @Key or Email like @Key) ";
                Key = model.Key.ToSqlLikeParam();
            }
            if (!model.RoleId.IsNullOrWhiteSpace())
            {
                conditions += $"and RoleId = { model.RoleId } ";
            }
            if (!model.State.IsNullOrWhiteSpace())
            {
                conditions += $"and State = { model.State  } ";
            }

            #endregion

            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc", new { Key = Key }).ToList();

            list.ForEach(x =>
            {
                var newEn = _desEncryptService.DecryptManagerInfo(x);
                var newX = EnManager(newEn);
                var item = _mapper.Map<ManagerListModel>(newX);
                item.RoleName = _roleRepository.GetNameById(x.RoleId);
                item.ParentRealName = _repository.GetUserNameAndRealNameById(x.AddManagerId);
                item.AuditImages = _dataRepository.GetAuditImagesById(x.Id);

                viewList.Add(item);
            });
            count = _repository.RecordCount(conditions, new { Key = Key });
            //}
            return new TableDataModel
            {
                count = count,
                data = viewList,
            };
        }

        /// <summary>
        /// 页面*加密
        /// </summary>
        /// <param name="manager"></param>
        /// <returns></returns>
        private Manager EnManager(Manager manager)
        {
            if (manager != null)
            {
                manager.QQ = manager.QQ == "error" ? "" : manager.QQ;
                manager.BankCard = manager.BankCard == "error" ? "" : manager.BankCard;
                manager.CardId = manager.CardId == "error" ? "" : manager.CardId;
                manager.Email = manager.Email == "error" ? "" : manager.Email;
                manager.Mobile = manager.Mobile == "error" ? "" : manager.Mobile;
                // 只有审核通过的用户加密相关数据
                if (manager.State == 1 && manager.IsLock == false)
                {
                    if (!manager.QQ.IsNullOrWhiteSpace() && manager.QQ.Length > 4)
                    {
                        manager.QQ = $"****{manager.QQ.Substring(manager.QQ.Length - 4, 4)}";
                    }
                    if (!manager.BankCard.IsNullOrWhiteSpace() && manager.BankCard.Length > 4)
                    {
                        manager.BankCard = $"****{manager.BankCard.Substring(manager.BankCard.Length - 4, 4)}";
                    }
                    if (!manager.CardId.IsNullOrWhiteSpace() && manager.CardId.Length > 4)
                    {
                        manager.CardId = $"****{manager.CardId.Substring(manager.CardId.Length - 4, 4)}";
                    }
                    if (!manager.Mobile.IsNullOrWhiteSpace() && manager.Mobile.Length == 11)
                    {
                        manager.Mobile = $"****{manager.Mobile.Substring(manager.Mobile.Length - 4, 4)}";
                    }
                    if (!manager.Email.IsNullOrWhiteSpace() && manager.Email.Length > 4 && manager.Email.IndexOf('@') != -1)
                    {
                        var emailArr = manager.Email.Split('@');
                        var first = emailArr[0] + (emailArr[0].Length > 4 ? "" : "****");
                        manager.Email = $"{first.Substring(0, 4)}****@{emailArr[1]}";
                    }
                }
            }
            return manager;
        }

        public BaseResult ChangeLockStatus(ChangeStatusModel model)
        {
            var result = new BaseResult();
            //判断状态是否发生变化，没有则修改，有则返回状态已变化无法更改状态的提示
            var isLock = _repository.GetLockStatusById(model.Id);
            if (isLock == !model.Status)
            {
                var count = _repository.ChangeLockStatusById(model.Id, model.Status);
                if (count > 0)
                {

                    var _manager = _repository.Get(model.Id);
                    if (_manager == null)
                    {
                        _logger.LogError($"直客视频回访逻辑!  未找到相关直客 Id：{model.Id}");
                    }
                    if (_manager.RoleId != 6)
                    {
                        _logger.LogWarning($"直客视频回访逻辑! 代理不需要视频回访 Id：{_manager.Id} RoleId：{_manager.RoleId}");
                    }
                    else
                    {
                        #region 风软注册
                        var rmmfCustomer = _mapper.Map<CustomerInput>(_manager);
                        if (rmmfCustomer != null)
                        {
                            var _pManager = _repository.Get(_manager.AddManagerId);
                            // 判断用户数据是否同步风软件
                            if (_pManager != null)
                            {
                                if (_manager.IsAsync)
                                {
                                    _logger.LogWarning($"直客审核二次回访逻辑! Id:{ _manager.Id} UserName：{ _manager.UserName}    RealName:{ _manager.RealName}    IsLock：{ _manager.IsLock}    State：{ _manager.State} AddTime:{ DateTime.Now }");
                                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                                }
                                else
                                {
                                    rmmfCustomer.RoleID = _rmmfService.RmmfCustomerRoleID;
                                    rmmfCustomer.LoginName = _manager.UserName;
                                    // 同步风软
                                    if (!_manager.RealName.IsNullOrWhiteSpace())
                                    {
                                        rmmfCustomer.First_Name = _manager.RealName.Substring(1);
                                        rmmfCustomer.Last_Name = _manager.RealName.Substring(0, 1);
                                    }
                                    // 明文传，不用加密
                                    // rmmfCustomer.Password = CzarCmsKeys.DefaultPassword;
                                    var defaultPwd = AESEncryptHelper.Decode(_manager.Password, CzarCmsKeys.AesEncryptKeys);
                                    rmmfCustomer.Password = defaultPwd;
                                    //rmmfCustomer.FirmStructureID = _rmmfService.AddRmmfFirmStructureByRoleId(_manager, _pManager.UserName);
                                    // 直客注册逻辑，上级代理为相关风软组织机构
                                    rmmfCustomer.FirmStructureID = _pManager.UserName;
                                    var rmmfFlag = _rmmfService.AddCustomer(rmmfCustomer);
                                    if (rmmfFlag > 0)
                                    {
                                        // 同步风软的用户编号
                                        _manager.RmmfUserId = rmmfFlag;
                                        _manager.IsAsync = true;
                                        _repository.Update(_manager);
                                        _logger.LogWarning($"直客视频回访逻辑! RmmfUserId:{rmmfFlag}  Id:{ _manager.Id} UserName：{ _manager.UserName}    RealName:{ _manager.RealName}    IsLock：{ _manager.IsLock}    State：{ _manager.State} AddTime:{ DateTime.Now }");
                                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                                    }
                                    else
                                    {
                                        _logger.LogError($"直客视频回访逻辑! 未找到直客的上级代理！ParentManagerID:{_manager.Id}");
                                        result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                                        result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                                    }
                                }
                            }
                            else
                            {
                                _logger.LogError($"直客视频回访逻辑! 未找到直客的上级代理！ParentManagerID:{_manager.AddManagerId}");
                                result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                                result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                            }
                        }
                        else
                        {
                            _logger.LogError($"直客视频回访逻辑! 同步风软实体映射失败！");
                            result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                            result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                        }
                        #endregion
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonDataStatusChangeCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonDataStatusChangeMsg;
            }
            return result;
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public TableDataResult<ManagerLoginModel> AddTerminal(ManagerTerminalRegisterModel model)
        {
            var result = new TableDataResult<ManagerLoginModel>();
            result.Success = false;

            var parentManagerId = DESEncryptHelper.Decrypt(model.UID).ToInt32() ?? 0;
            #region 1. 验证邮箱是否存在
            // 1. 验证用户名是否存在
            // 2. 验证邮箱是否存在
            var __email__ = _desEncryptService.EncryptEmail(model.Email);
            var _email = _repository.Get($"select * from Manager where IsDelete=0 AND  Email='{ __email__ }' ");
            if (_email != null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.RegisterEmailExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.RegisterEmailExceptionMsg;
                return result;
            }
            #endregion

            #region 2.验证身份证是否存在
            var __cardId__ = _desEncryptService.EncryptCardId(model.CardId);
            var _CardId = _repository.Get($"select * from Manager where IsDelete=0 AND CardId='{ __cardId__ }'");
            if (_CardId != null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.RegisterCardIdExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.RegisterCardIdExceptionMsg;
                return result;
            }
            #endregion
            ///APP只直客注册
            if (model.Source == "App")
            {
                var _userId = 0;
                var resultManagerId = AESEncryptHelper.Decode(model.Reg, CzarCmsKeys.AesEncryptKeys);
                if (int.TryParse(resultManagerId, out _userId))
                {
                    var managerInfo = _repository.Get(_userId);
                    if (managerInfo.IsLock)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionMsg;
                        return result;
                    }
                    parentManagerId = _userId;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionMsg;
                    return result;
                }
            }
            else
            {

                #region 3. 验证直客注册码是否正确
                // 3. 验证直客注册码是否正确
                var _token = _tokenRepository.Get($"select * from ManagerToken where ManagerId='{ parentManagerId }' and Token= '{ model.Reg }'");
                if (_token == null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.RegisterTokenExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.RegisterTokenExceptionMsg;
                    return result;
                }
                else if (_token.IsUsed.HasValue && _token.IsUsed.Value)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.RegisterTokenExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.RegisterTokenExceptionMsg;
                    return result;
                }
                else
                {
                    _token.IsUsed = true;
                    _tokenRepository.Update(_token);
                }
                #endregion

            }


            var now = DateTime.Now;
            Manager manager;
            //TODO ADD
            manager = _mapper.Map<Manager>(model);
            //manager.Password = AESEncryptHelper.Encode(manager.Password, CzarCmsKeys.AesEncryptKeys);
            var maxManager = _repository.Get($"select top 1 * from Manager order by Id desc");
            var _userRnd = 100001 + (maxManager == null ? 0 : maxManager.Id);
            manager.UserName = $"QS{ _userRnd }";
#if DEBUG
            //  manager.UserName = $"TEST{ _userRnd }";
#endif
            //manager.Password = AESEncryptHelper.Encode(CzarCmsKeys.DefaultPassword, CzarCmsKeys.AesEncryptKeys);
            var defaultPwd = model.CardId.Substring(model.CardId.Length - 6);
            manager.Password = AESEncryptHelper.Encode(defaultPwd, CzarCmsKeys.AesEncryptKeys);

            manager.LoginCount = 0;
            manager.RoleId = 6; // 3：分别为一级代理；4：二级代理； 5：中级代理6:直客
            manager.AddManagerId = parentManagerId;
            manager.NickName = model.RealName;
            manager.IsDelete = false;
            // 未回访，Lock
            manager.IsLock = true;
            manager.State = 0;
            manager.AddTime = now;
            _logger.LogWarning($"用户注册: Id:{ manager.Id} UserName：{ manager.UserName}    RealName:{ manager.RealName}    IsLock：{ manager.IsLock}    State：{ manager.State} AddTime:{ now }  Source:{model.Source }");

            using (TransactionScope scope = new TransactionScope())
            {
                manager = _desEncryptService.EncryptManagerInfo(manager);
                var managerId = _repository.Insert(manager);
                if (managerId > 0)
                {
                    if (model.AuditImages.Any())
                    {
                        foreach (var auditImageUrl in model.AuditImages)
                        {
                            _dataRepository.Insert(new ManagerData
                            {
                                ImageUrl = auditImageUrl,
                                ManagerId = managerId,
                                AddTime = now
                            });
                        }
                    }

                    result.Data = new ManagerLoginModel { UserName = manager.UserName, Password = defaultPwd };
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    result.Success = true;

                    scope.Complete();
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                }
            }

            return result;
        }

        public BaseResult AddAgent(ManagerAgentRegisterModel model)
        {
            var result = new BaseResult();

            #region 1.验证用户名已存在

            var _user = _repository.Get($"select * from Manager where IsDelete=0 AND UserName='{ model.UserName }' ");
            if (_user != null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.RegisterExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.RegisterExceptionMsg;
                return result;
            }

            #endregion

            #region 2.验证身份证已存在

            var cardId = _desEncryptService.EncryptCardId(model.CardId);
            var _card = _repository.Get($"select * from Manager where IsDelete=0 AND  CardId='{ cardId }' ");
            if (_card != null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.RegisterCardIdExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.RegisterCardIdExceptionMsg;
                return result;
            }

            #endregion

            #region 2. 验证用户推荐码是否正确
            int roleId = 2;
            int? _managerId = 0;
            if (!model.InvitationCode.Contains("GaoTang"))
            {
                _managerId = AESEncryptHelper.Decode(model.InvitationCode, CzarCmsKeys.AesEncryptKeys).ToInt32();
                if (_managerId == 0)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionMsg;
                    return result;
                }
                var _parentUser = _repository.Get(_managerId.Value);

                if (_parentUser == null)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.RegisterInvitationCodeExceptionMsg;
                    return result;
                }
                else
                {
                    roleId = _parentUser.RoleId;

                    if (roleId != 3)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.RegisterAgentExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.RegisterAgentExceptionMsg;
                        return result;
                    }
                }
            }

            #endregion

            #region 3. 判断用户用色
            var now = DateTime.Now;
            Manager manager = _mapper.Map<Manager>(model);
            manager.Password = AESEncryptHelper.Encode(manager.Password, CzarCmsKeys.AesEncryptKeys);
            manager.LoginCount = 0;
            manager.RoleId = roleId + 1; // 3：分别为一级代理；4：二级代理； 5：中级代理
            manager.AddManagerId = _managerId.Value;
            manager.NickName = model.RealName;
            manager.IsDelete = false;
            manager.AddTime = now;
            #endregion

            #region 4.1 代理注册

            manager = _desEncryptService.EncryptManagerInfo(manager);

            var managerId = _repository.Insert(manager);
            if (managerId > 0)
            {
                if (model.AuditImages.Any())
                {
                    foreach (var auditImageUrl in model.AuditImages)
                    {
                        _dataRepository.Insert(new ManagerData
                        {
                            ImageUrl = auditImageUrl,
                            ManagerId = managerId,
                            AddTime = now
                        });
                    }
                }

                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }
            #endregion

            return result;
        }

        public TableDataResult<Manager> Login(String userName, String pwd)
        {
            var result = new TableDataResult<Manager>();
            result.Success = false;
            // 已审核的用户
            string conditions = $"select * from Manager where UserName='{ userName }' ";
            var manager = _repository.Get(conditions);

            if (manager != null)
            {
                // 密码
                string password = AESEncryptHelper.Encode(pwd, CzarCmsKeys.AesEncryptKeys);
                if (password != manager.Password)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.LoginPasswordExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.LoginPasswordExceptionMsg;
                }
                else
                {
                    manager = _desEncryptService.DecryptManagerInfo(manager);

                    result.Data = manager;
                    _managerLogRepository.Insert(new ManagerLog()
                    {
                        ActionType = CzarCmsEnums.ActionEnum.SignIn.ToString(),
                        AddManageId = manager.Id,
                        AddManagerNickName = manager.NickName,
                        AddTime = DateTime.Now,
                        Remark = "用户登录App"
                    });
                    CacheHelper.Set(Constants.CACHE_USERINFO, manager);
                    result.Success = true;
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.LoginUserExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.LoginUserExceptionMsg;
            }

            return result;
        }

        /// <summary>
        /// 登录操作，成功则写日志
        /// </summary>
        /// <param name="model">登陆实体</param>
        /// <returns>状态</returns>
        public Manager SignIn(LoginModel model)
        {
            model.Password = AESEncryptHelper.Encode(model.Password.Trim(), CzarCmsKeys.AesEncryptKeys);
            model.UserName = model.UserName.Trim();
            string conditions = "where IsDelete=0 ";//未删除的
            conditions += $"and (UserName = @UserName or Mobile =@UserName or Email =@UserName) and Password=@Password";
            var manager = _repository.GetList(conditions, model).FirstOrDefault();
            if (manager != null)
            {
                manager.LoginLastIp = model.Ip;
                manager.LoginCount += 1;
                manager.LoginLastTime = DateTime.Now;
                _repository.Update(manager);
                _managerLogRepository.Insert(new ManagerLog()
                {
                    ActionType = CzarCmsEnums.ActionEnum.SignIn.ToString(),
                    AddManageId = manager.Id,
                    AddManagerNickName = manager.NickName,
                    AddTime = DateTime.Now,
                    AddIp = model.Ip,
                    Remark = "用户登录"
                });
                manager = _desEncryptService.DecryptManagerInfo(manager);
            }

            return manager;
        }

        /// <summary>
        /// 审核账户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public BaseResult AuditRegister(ManagerAuditRegisterModel model)
        {
            var result = new BaseResult();

            var _manager = _repository.Get(model.Id);
            if (_manager != null)
            {
                if (_manager.State.HasValue && _manager.State.Value > 0)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.AuditExceptionCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.AuditExceptionMsg;
                }
                else
                {
                    _manager = _desEncryptService.DecryptManagerInfo(_manager);
                    //复制银行卡到 ManagerBankCard表
                    _managerBankCard.AddBankCard(_mapper.Map<ManagerModifyBankCardModel>(_manager));

                    // 直客只修改状态，等视频回访逻辑时同步风软
                    if (_manager.RoleId == 6)
                    {
                        _logger.LogWarning($"直客审核等视频回访逻辑时同步风软Id:{ _manager.Id} UserName：{ _manager.UserName}    RealName:{ _manager.RealName}    IsLock：{ _manager.IsLock}    State：{ _manager.State} AddTime:{ DateTime.Now }");
                        _manager.State = model.State;
                        _manager = _desEncryptService.EncryptManagerInfo(_manager);
                        if (_repository.Update(_manager) > 0)
                        {
                            result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                            result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                        }
                        else
                        {
                            result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                            result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                        }
                    }
                    else
                    {
                        #region 风软注册
                        var rmmfCustomer = _mapper.Map<CustomerInput>(_manager);
                        if (rmmfCustomer != null)
                        {
                            var _pManager = _repository.Get(_manager.AddManagerId);
                            // 判断用户数据是否同步风软件
                            if (_pManager != null)
                            {
                                _manager = _desEncryptService.EncryptManagerInfo(_manager);
                                if (_manager.IsAsync)
                                {
                                    _manager.State = model.State;
                                    _repository.Update(_manager);
                                    _logger.LogWarning($"代理二次审核不同步风软! Id:{ _manager.Id} UserName：{ _manager.UserName}    RealName:{ _manager.RealName}    IsLock：{ _manager.IsLock}    State：{ _manager.State} AddTime:{ DateTime.Now }");
                                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                                }
                                else
                                {
                                    rmmfCustomer.RoleID = _rmmfService.RmmfCustomerRoleID;
                                    rmmfCustomer.LoginName = _manager.UserName;
                                    // 明文传，不用加密
                                    //rmmfCustomer.Password = CzarCmsKeys.DefaultPassword;
                                    var defaultPwd = AESEncryptHelper.Decode(_manager.Password, CzarCmsKeys.AesEncryptKeys);
                                    rmmfCustomer.Password = defaultPwd;
                                    // 同步风软
                                    if (!_manager.RealName.IsNullOrWhiteSpace())
                                    {
                                        rmmfCustomer.First_Name = _manager.RealName.Substring(1);
                                        rmmfCustomer.Last_Name = _manager.RealName.Substring(0, 1);
                                    }
                                    //创建组织
                                    rmmfCustomer.FirmStructureID = _rmmfService.AddRmmfFirmStructureByRoleId(_manager, _pManager.UserName);
                                    //
                                    var rmmfFlag = _rmmfService.AddCustomer(rmmfCustomer);
                                    if (rmmfFlag > 0)
                                    {
                                        // 同步风软的用户编号
                                        _manager.RmmfUserId = rmmfFlag;
                                        _manager.State = model.State;
                                        _manager.IsAsync = true; // 已同步风软
                                        _repository.Update(_manager);
                                        _logger.LogWarning($"代理审核已同步风软! RmmfUserId:{rmmfFlag}  Id:{ _manager.Id} UserName：{ _manager.UserName}    RealName:{ _manager.RealName}    IsLock：{ _manager.IsLock}    State：{ _manager.State} AddTime:{ DateTime.Now }");
                                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                                    }
                                    else
                                    {
                                        result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                                        result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                                    }
                                }
                            }
                            else
                            {
                                result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                                result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                            }
                        }
                        else
                        {
                            result.ResultCode = ResultCodeAddMsgKeys.RmmfRegisterExceptionCode;
                            result.ResultMsg = ResultCodeAddMsgKeys.RmmfRegisterExceptionMsg;
                        }
                        #endregion
                    }
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }
            return result;
        }

        public ManagerListModel GetManagerById(string userId)
        {
            var _userId = 0;
            if (int.TryParse(userId, out _userId))
            {
                var manager = _repository.Get(_userId);
                if (manager != null)
                {
                    manager = _desEncryptService.DecryptManagerInfo(manager);

                    var user = _mapper.Map<ManagerListModel>(manager);
                    user.AuditImages = _dataRepository.GetAuditImagesById(_userId);
                    return user;
                }
            }
            return null;
        }

        public TableDataResult<List<ManagerTreeItem>> GetCacheAllManager(String UserId, String RoleId)
        {
            var result = new TableDataResult<List<ManagerTreeItem>>();

            string conditions = "where IsDelete=0 and State = 1 ";//未删除和已审核

            #region 获取相关用户的处理逻辑

            var _managers = GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId, false);
            if (_managers.Any()) conditions += $"and Id in({ String.Join(',', _managers.Select(p => p.ItemCode)) }) ";

            #endregion

            var allUser = _repository.GetList(conditions).OrderBy(o => o.RoleId);
            var currentUser = _repository.Get(UserId.ToInt32() ?? 0);
            if (currentUser == null)
            {
                return result;
            }

            #region 结构树

            var users = new List<ManagerTreeItem>();
            var source = new List<ManagerTreeItem>();
            var _parentId = currentUser.AddManagerId.ToString();
            foreach (var _user in allUser)
            {
                source.Add(new ManagerTreeItem
                {
                    Id = _user.Id.ToString(),
                    IsRoot = false,
                    IsLeaf = false,
                    ParentId = _user.AddManagerId.ToString(),
                    RoleId = _user.RoleId,
                    UserName = _user.UserName,
                    RealName = _user.RealName,
                });
            }
            InitTree(users, _parentId, source);

            #endregion

            result.Data = users;
            return result;
        }

        /// <summary>
        /// 递归初始化树
        /// </summary>
        /// <param name="nodes">结果</param>
        /// <param name="parentID">父ID</param>
        /// <param name="sources">数据源</param>
        private void InitTree(IList<ManagerTreeItem> nodes, string parentID, IList<ManagerTreeItem> sources)
        {
            ManagerTreeItem tempNode;
            //递归寻找子节点  
            var tempTree = sources.Where(item => item.ParentId == parentID).ToList();
            foreach (ManagerTreeItem row in tempTree)
            {
                tempNode = new ManagerTreeItem()
                {
                    Id = row.Id,
                    IsRoot = false,
                    IsLeaf = true,
                    ParentId = row.ParentId,
                    RoleId = row.RoleId,
                    UserName = row.UserName,
                    RealName = row.RealName,
                    Items = new List<ManagerTreeItem>()
                };
                nodes.Add(tempNode);
                InitTree(tempNode.Items, row.Id, sources);
            }
        }

        public BooleanResult EditPassword(PasswordModel model)
        {
            var result = new BooleanResult();
            var managerId = 0;
            if (!int.TryParse(model.Id, out managerId))
                return result;

            var manager = _repository.Get(managerId);
            //if (!manager.RmmfUserId.HasValue)
            //    return result;
            if (manager == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }
            else
            {
                var oldPwd = AESEncryptHelper.Encode(model.Password, CzarCmsKeys.AesEncryptKeys);
                if (oldPwd != manager.Password)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.OldPasswordErrorCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.OldPasswordErrorMsg;
                }
                else
                {
                    manager.Password = AESEncryptHelper.Encode(model.NewPassword, CzarCmsKeys.AesEncryptKeys);
                    manager.ModifyTime = DateTime.Now;
                    manager.ModifyManagerId = managerId;

                    #region 同步风软修改密码功能
                    //_rmmfService.ResetLoginUserPassword()
                    #endregion

                    var flag = _repository.Update(manager);
                    result.Data = flag > 0;
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
            }

            return result;
        }

        /// <summary>
        /// 获取附属用户
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public TableDataResult<List<ManagerSubItem>> GetCacheSubManagerByUserId(String UserId, String RoleId)
        {
            var result = new TableDataResult<List<ManagerSubItem>>();

            string conditions = "where IsDelete=0 and State = 1 ";//未删除和已审核

            #region 获取相关用户的处理逻辑

            if (RoleId == "1" || RoleId == "2")
            {
                conditions += " AND RoleId in(3,4,5) ";
            }
            else
            {
                var _managers = GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId, false);
                if (_managers.Any()) conditions += $"and Id in({ String.Join(',', _managers.Select(p => p.ItemCode)) }) ";
            }
            #endregion

            var allUser = _repository.GetList(conditions).OrderBy(o => o.RoleId);
            var currentUser = _repository.Get(UserId.ToInt32() ?? 0);
            if (currentUser == null)
            {
                return result;
            }
            #region
            var users = new List<ManagerSubItem>();
            var source = new List<ManagerSubItem>();
            foreach (var _user in allUser)
            {
                users.Add(new ManagerSubItem
                {
                    Id = _user.Id.ToString(),
                    ParentId = _user.AddManagerId.ToString(),
                    RoleId = _user.RoleId,
                    UserName = _user.UserName,
                    RealName = _user.RealName,
                });
            }
            #endregion
            result.Data = users;
            return result;

        }

        /// <summary>
        /// 驳回原因
        /// </summary>
        /// <param name="managerId"></param>
        /// <param name="auditRemark"></param>
        /// <returns></returns>
        public BaseResult AddAuditRemark(int managerId, string auditRemark)
        {
            var result = new BaseResult();
            var manager = _repository.Get(managerId);
            if (manager != null)
            {
                manager.State = 2;
                manager.AuditRemark = auditRemark;
                if (_repository.Update(manager) > 0)
                {
                    result.Success = true;
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }

            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
            }
            return result;
        }


        public int? GetManagerStateByManagerId(string UserId)
        {
            int? state = 0;
            var _userId = 0;
            if (int.TryParse(UserId, out _userId))
            {
                var data = _repository.Get(_userId);
                if (data != null)
                {
                    state = data.State;
                }
            }
            return state;
        }

        public TableDataResult<Manager> GetManagerTableById(string ManagerId)
        {
            var result = new TableDataResult<Manager>();
            var _managerId = 0;
            if (int.TryParse(ManagerId, out _managerId))
            {
                var _manager = _repository.Get(_managerId);
                result.Data = _manager;
            }

            return result;
        }

        /// <summary>
        /// 解密用户信息
        /// </summary>
        public Manager DecryptManagerInfoById(int managerId)
        {
            Manager result = default(Manager);
            var entity = _repository.Get(managerId);
            if (entity != null)
            {
                result = _desEncryptService.DecryptManagerInfo(entity);
            }

            return result;
        }

        /// <summary>
        /// 特殊代理隐藏手机检查
        /// </summary>
        /// <param name="UID"></param>
        /// <returns></returns>
        public Boolean CheckSpecialAgentIsHiddenPhoneByUID(string UID)
        {

            var AgentUserId = DESEncryptHelper.Decrypt(UID) ?? null;
            if (AgentUserId !=null)
            {
                var SpecialAgentUserId = _configuration["SpecialAgent:HidePhoneAgentUserId"];
                string[]  arr =  SpecialAgentUserId.Split(",");
               var result =   arr.Contains(AgentUserId);
                return result;
            }

            return false;

        }

        //public List<ItemsDetailModel> GetCacheAllAgentManager(String UserId = "", String RoleId = "")
        //{
        //    var result = new List<ItemsDetailModel>();
        //    string conditions = "where IsDelete=0 and State = 1 and RoleId in(3, 4)";// 未删除和已审核
        //    if (!UserId.IsNullOrWhiteSpace())
        //    {
        //        conditions += $" and (Id={UserId} or AddManagerId = {UserId})";
        //    }
        //    var allUser = _repository.GetList(conditions);
        //    if (allUser.Any())
        //    {
        //        foreach (var user in allUser)
        //        {
        //            result.Add(new ItemsDetailModel
        //            {
        //                ItemName = user.UserName,
        //                ItemData = user.RealName,
        //                ItemCode = user.Id.ToString()
        //            });
        //        }
        //    }
        //    return result;
        //}

    }
}